import { store } from "@/store";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useDictStoreHook } from "@/store/modules/dict";

import AuthAPI, { type ChangePaswwordForm, type LoginData } from "@/api/auth";
import {
  type MerchantInfoType,
  type AgentInfoType,
  type SupplierInfoType,
  type UserInfo,
} from "@/api/system/user";

import { setToken, setRefreshToken, getRefreshToken, clearToken } from "@/utils/auth";
import CONFIG_API from "@/api/system";

export const useUserStore = defineStore("user", () => {
  const userInfo = useStorage<UserInfo>("userInfo", {
    roles: [],
    is_superuser: false,
    id: 0,
    username: "",
    nickname: "",
    avatar_url: "",
    balance: "",
    is_staff: false,
    is_supplier: false,
  } as UserInfo);
  const isSupplier = useStorage("isSupplier", false);
  const isAgent = useStorage("isAgent", false);
  const userGroups = useStorage("userGroups", {});
  const supplierInfo = useStorage<SupplierInfoType>("supplierInfo", {
    agent: undefined,
    bill_amount: "",
    bill_amount_freeze: "",
    bill_amount_withdrawn: "",
    contact_email: "",
    contact_name: "",
    contact_phone: "",
    id: 0,
    is_active: false,
    name: "",
    user: 0,
  });
  const merchantInfo = useStorage<MerchantInfoType | null>("merchantInfo", null);
  const agentInfo = useStorage<AgentInfoType | null>("agentInfo", null);
  const config = useStorage("config", {});
  const loading = reactive({
    changePassword: false,
  });

  /**
   * 登录
   *
   * @returns
  const agentInfo = useStorage<AgentInfoType | null>("agentInfo", null);
  const config = useStorage("config", {});

  /**
   * 登录
   *
   * @returns
   * @param loginData
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          const { access, refresh } = data;
          setToken("Bearer " + access); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          setRefreshToken(refresh);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取用户信息
   * @returns 用户信息
   */
  function getUserInfo() {
    return new Promise<UserInfo>((resolve, reject) => {
      AuthAPI.userInfo()
        .then((data) => {
          if (!data) {
            reject("Verification failed, please Login again.");
            return;
          }
          data.roles = [];
          if (data.is_staff) {
            data.roles.push("staffer");
          }
          if (data.is_superuser) {
            data.roles.push("superuser");
          }
          userInfo.value = data;
          // Object.assign(userInfo.value, { ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取用户角色
   * @returns 用户角色
   */
  function getUserGroups() {
    return new Promise((resolve, reject) => {
      AuthAPI.userGroups()
        .then((data) => {
          userGroups.value = data;
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取商户信息
   * @returns 商户角色
   */
  function getSupplierInfo() {
    return new Promise((resolve, reject) => {
      AuthAPI.supplierInfo()
        .then((res: any) => {
          supplierInfo.value = res.data.info || {};
          isSupplier.value = res.data.is_supplier;
          if (res.data.is_supplier) {
            userInfo.value.roles.push("supplier");
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function getMerchangtInfo() {
    return new Promise((resolve, reject) => {
      AuthAPI.merchantInfo()
        .then((res) => {
          if (res.data?.is_merchant) {
            userInfo.value.roles.push("merchanter");
            merchantInfo.value = res.data.info;
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function getAgentInfo() {
    return new Promise((resolve, reject) => {
      AuthAPI.agentInfo()
        .then((res) => {
          if (res.data?.is_agent) {
            isAgent.value = res.data.is_agent;
            userInfo.value.roles.push("agenter");
            agentInfo.value = res.data.info;
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function getSystemConfig() {
    return new Promise((resolve, reject) => {
      CONFIG_API.getConfig()
        .then((res: any) => {
          config.value = res.data || {};
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 登出
   */
  function logout() {
    return new Promise<void>((resolve) => {
      clearUserData().then();
      resolve();
      // AuthAPI.logout()
      //   .then(() => {
      //     clearUserData();
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  }

  /**
   * 刷新 token
   */
  function refreshToken() {
    const refreshToken = getRefreshToken();
    return new Promise<void>((resolve, reject) => {
      AuthAPI.refreshToken(refreshToken)
        .then((data) => {
          const { token } = data;
          setToken("Bearer " + token);
          setRefreshToken(token);
          resolve();
        })
        .catch((error) => {
          console.log(" refreshToken  刷新失败", error);
          reject(error);
        });
    });
  }

  /**
   * @description 清理用户数据
   * @returns Promise<void>
   */
  function clearUserData() {
    return new Promise<void>((resolve) => {
      clearToken();
      usePermissionStoreHook().resetRouter();
      useDictStoreHook().clearDictionaryCache();
      resolve();
      localStorage.clear();
    });
  }

  function fetchBindInviteCode(code: string) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.bindInviteCode(code)
        .then(() => {
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  function fetchChangePassword(data: ChangePaswwordForm) {
    return new Promise<void>((resolve, reject) => {
      loading.changePassword = true;
      AuthAPI.changePassword(data)
        .then(() => {
          loading.changePassword = false;
          // 退出登录
          resolve();
        })
        .catch((error) => {
          loading.changePassword = false;
          reject(error);
        });
    });
  }

  return {
    userInfo,
    userGroups,
    config,
    isSupplier,
    isAgent,
    supplierInfo,
    getUserInfo,
    getUserGroups,
    getSupplierInfo,
    getMerchangtInfo,
    getAgentInfo,
    agentInfo,
    getSystemConfig,
    fetchBindInviteCode,
    login,
    logout,
    clearUserData,
    refreshToken,
    fetchChangePassword,
    loading,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
